const _ = require('lodash');
const { clone } = require('./util');

const sum = arr => (_.sum(arr) + arr.length - 1);

const newArr = (len, val) => (new Array(len).fill(val));

const _solve = (base, hint) => {
    let res = [];
    // console.log('base as:')
    // console.log(base);
    if (hint.length) {
        let maxLeft = base.length - sum(hint);
        for (let offset = 0; offset <= maxLeft; offset++) {
            let offsetStr = newArr(offset, -1);
            let currStr = newArr(hint[0], 1)

            let _curr = _.concat(offsetStr, currStr);

            let leftArr = base.slice(offset + hint[0] + 1);
            let leftHint = hint.slice(1)

            let possible = _solve(leftArr, leftHint);

            let isLast = offset + hint[0] + 1 > base.length;
            // console.log('Possibles:')
            // console.log(possible);

            let solutions = possible.map(item => (isLast ? _curr : _.concat(_curr, -1, item)))

            res = res.concat(solutions)
        }
    } else {
        res = [clone(base).fill(-1)];
    }
    // console.log('res as:')
    // console.log(res);
    // console.log('\n')
    return res;
}

const getSharedPart = (solutions, base) => {
    let arr = solutions.filter(s => {
        return base.reduce((prev, curr, index) => {
            return prev && (curr === 0 || curr === s[index])
        }, true)
    })

    let res = clone(arr[0]);

    // console.log(arr)

    arr.map(s => {
        for (let i = 0; i < s.length; i++) {
            if (res[i] !== 0 && res[i] !== s[i]) {
                res[i] = 0;
            }
        }
    })

    return res;
}

// [-1,1,0,0,0,0,0,0] [3,2]
const enumerate = (base, hint) => {
    let solutions = _solve(base, hint);
    let res = getSharedPart(solutions, base);
    // console.log('===================')
    // console.log(solutions);
    // console.log(res);
    return res;
}

// enumerate([1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [3, 2, 2]);

// enumerate([1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4, 3]);

// enumerate([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [8]);

// enumerate([0, 0, 0, 0, 0, 0, 0], [4]);

module.exports = {
    enumerate,
}